<?php
/**
 * User: bgl
 * Date: 2023/5/6
 * Time: 9:18
 */

namespace App\Admin\Controllers\ProductStockup;


use App\Admin\Actions\ProductStockup\CheckboxBatchApply;
use App\Admin\Actions\ProductStockup\ImportSku;
use App\Admin\Actions\ProductStockup\ImportStockupItem;
use App\Admin\Ajax\ProductsStockup\StockupAjax;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Exporter\ProductStockup\StockupExporter;
use App\Models\Basics\SysArea;
use App\Models\Product\ProductClassify;
use App\Models\ProductStockup\Stockup;
use App\Models\SsBasic\StockupAreaSkuEstimate;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;

class StockupApplyController extends AdminController{

    protected $title = '产品备货申请（新）';

    protected function grid(){

        Admin::style($this->_style());
        $grid = new Grid(new Stockup());
        $grid->model()->groupBy('classify_id')->orderByDesc('id');
        $grid->model()->collection(function (Collection $collection) use ($grid){

            foreach ($collection as $item){
                $item->recommend_num = Stockup::getStockupColumnSum($item->classify_id, 'recommend_num');
                $item->apply_num = Stockup::getStockupColumnSum($item->classify_id, 'apply_num');
                $item->approval_num = Stockup::getStockupColumnSum($item->classify_id, 'approval_num');
                $item->confirm_num = Stockup::getStockupColumnSum($item->classify_id, 'confirm_num');

                $item->fba_instant_num = Stockup::getStockupColumnSum($item->classify_id, 'fba_instant_num');
                $item->fba_transit_num = Stockup::getStockupColumnSum($item->classify_id, 'fba_transit_num');
                $item->cn_instant_num = Stockup::getStockupColumnSum($item->classify_id, 'cn_instant_num');
                $item->cn_transit_num = Stockup::getStockupColumnSum($item->classify_id, 'cn_transit_num');
                $item->os_instant_num = Stockup::getStockupColumnSum($item->classify_id, 'os_instant_num');
                $item->os_transit_num = Stockup::getStockupColumnSum($item->classify_id, 'os_transit_num');
                $item->stock_total = Stockup::getStockupColumnSum($item->classify_id, 'stock_total');
                $item->cn_pulic_instant_num = Stockup::getStockupColumnSum($item->classify_id, 'cn_pulic_instant_num');
                $item->cn_stock_total = Stockup::getStockupColumnSum($item->classify_id, 'cn_stock_total');
                $item->overstock_num = Stockup::getStockupColumnSum($item->classify_id, 'overstock_num');
                $item->divert_overstock_num = Stockup::getStockupColumnSum($item->classify_id, 'divert_overstock_num');
                $item->divert_instant_num = Stockup::getStockupColumnSum($item->classify_id, 'divert_instant_num');
                $item->divert_transit_num = Stockup::getStockupColumnSum($item->classify_id, 'divert_transit_num');
                $item->defer_stock_num = Stockup::getStockupColumnSum($item->classify_id, 'defer_stock_num');

                $item->current_sale_ratio = Stockup::getStockupColumnSum($item->classify_id, 'current_sale_ratio');
                $item->volume3_avg = Stockup::getStockupColumnSum($item->classify_id, 'volume3_avg');
                $item->volume30_avg = Stockup::getStockupColumnSum($item->classify_id, 'volume30_avg');
                $item->volume30_ratio = Stockup::getStockupColumnSum($item->classify_id, 'volume30_ratio');
                $item->ratio = Stockup::getStockupColumnSum($item->classify_id, 'ratio');

                for($i = 0; $i < StockupAreaSkuEstimate::NEW_ESTIMATE_NUM; $i++){
                    $item->{'estimate_num'.$i} = Stockup::getStockupColumnSum($item->classify_id, 'estimate_num'.$i);
                }
            }
            return $collection;
        });

        $grid->column('checkbox1','选项')->totalRow('合计');
        $grid->column('classify.title','品类')->expand(function ($model) use($grid){

            $classifySku = Stockup::getClassifySku($model->classify_id);
            $classifyArea = Stockup::getClassifyArea($model->classify_id);

            return view('product-stockup.stockup-apply.index', compact('classifySku', 'classifyArea'));
        })->style('width: 300px; display: block; border-bottom: 0px solid #f4f4f4; overflow: hidden; text-overflow: ellipsis;');

        $grid->column('area.area','站点')->display(function (){
            return '';
        })->style('width: 44px;');
        $grid->column('sku.psku_code','SKU编号')->display(function (){
            return '';
        })->style('width: 70px;');
        $grid->column('sku.psku_cn','SKU名称')->display(function (){
            return '';
        })->style('width: 350px; display: block; border-bottom: 0px solid #f4f4f4; padding-top: 15px; overflow: hidden; text-overflow: ellipsis;');

        $grid->column('recommend_num','推荐备货数量')->totalRow(function($value) use($grid){
            return Stockup::getStockupColumnSum(null, 'recommend_num');
        });
        $grid->column('apply_num','申请数量')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'apply_num');
        });
        $grid->column('apply_remark','申请备注')->display(function (){
            return '';
        });
        $grid->column('approval_num','审批数量')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'approval_num');
        });
        $grid->column('approval_remark','审批备注')->display(function (){
            return '';
        });
        $grid->column('confirm_num','确认数量')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'confirm_num');
        });
        $grid->column('confirm_remark','确认备注')->display(function (){
            return '';
        });
        $grid->column('status','备货状态')->display(function (){
            return '';
        });

        $grid->column('current_sale_ratio','最近旺季销售比例')->totalRow(function (){
            return Stockup::getStockupColumnSum(null, 'current_sale_ratio');
        });
        $grid->column('volume3_avg','最近3天平均销量')->totalRow(function (){
            return Stockup::getStockupColumnSum(null, 'volume3_avg');
        });
        $grid->column('volume30_avg','最近30天平均销量')->totalRow(function (){
            return Stockup::getStockupColumnSum(null, 'volume30_avg');
        });
        $grid->column('volume30_ratio','最近30天销售比例')->totalRow(function (){
            return Stockup::getStockupColumnSum(null, 'volume30_ratio');
        });
        $grid->column('ratio','确定后的销售比例')->totalRow(function (){
            return Stockup::getStockupColumnSum(null, 'ratio');
        });

        $grid->column('fba_instant_num','FBA在库')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'fba_instant_num');
        });
        $grid->column('fba_transit_num','FBA在途')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'fba_transit_num');
        });
        $grid->column('cn_instant_num','国内在库')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'cn_instant_num');
        });
        $grid->column('cn_transit_num','国内在途')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'cn_transit_num');
        });
        $grid->column('os_instant_num','海外仓在库')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'os_instant_num');
        });
        $grid->column('os_transit_num','海外仓在途')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'os_transit_num');
        });
        $grid->column('dispense_num','分配数量')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'dispense_num');
        });
        $grid->column('dispense_surplus_num','分配剩余')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'dispense_surplus_num');
        });
        $grid->column('stock_total','库存总量')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'stock_total');
        });

        for($i = 0; $i < StockupAreaSkuEstimate::NEW_ESTIMATE_NUM; $i++){
            $grid->column('estimate_num'.$i,date('y/m',strtotime("midnight first day of $i month")).'预估')->totalRow(function () use($i){
                return Stockup::getStockupColumnSum(null, 'estimate_num'.$i);
            });
        }
        $grid->column('estimate_total','预估总量')->totalRow(function (){
            return Stockup::getStockupColumnSum(null, 'estimate_total');
        });
        $grid->column('estimate_growth_rate','同期增长率')->totalRow(function (){
            return Stockup::getStockupColumnSum(null, 'estimate_growth_rate');
        });

        $grid->column('cn_pulic_instant_num','公共在库数量')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'cn_pulic_instant_num');
        })->help('（public）');
        $grid->column('cn_stock_total','中国库存总量')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'cn_stock_total');
        })->help('（public）');
        $grid->column('overstock_num','备货推荐和总积压库存')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'overstock_num');
        });
        $grid->column('divert_overstock_num','总库存可挪用积压')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'divert_overstock_num');
        });
        $grid->column('divert_instant_num','中国在库库存可挪用积压')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'divert_instant_num');
        });
        $grid->column('divert_transit_num','中国在途库存可挪用积压')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'divert_transit_num');
        });
        $grid->column('defer_stock_num','阶段性可挪用在库存')->totalRow(function(){
            return Stockup::getStockupColumnSum(null, 'defer_stock_num');
        });

        $script = <<<SCRIPT
            $(function($){
               $(".table tfoot:first").css({'color':'red'});
            });
SCRIPT;
       Admin::script($script);

        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new CheckboxBatchApply()); //全选
            $tools->append(new ImportStockupItem());
        });

        $grid->disableRowSelector();
        $grid->disableCreateButton();
        $grid->disableActions();
        $grid->expandFilter();
        $grid->paginate(10);
        $grid->exporter(new StockupExporter());

        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('area_id','站点')->select(SysArea::options());

            });
            $filter->column(1/2, function ($filter) {
                $filter->equal('classify.season', '季节性')->select(ProductClassify::$_season);
                $filter->equal('classify_id', '品类')->select(ProductClassify::options());
            });
        });

        return $grid;
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new StockupAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function update($id){

        DB::beginTransaction();
        try{
            $name = Request::get('name');
            $value = Request::get('value');

            if($name == 'recommend_num') $value = intval($value);
            if($name == 'approval_num') $value = intval($value);
            if($name == 'confirm_num') $value = intval($value);

            if($name == 'recommend_num' && $value <= 0) return response()->json(['status' => false, 'message' => '数量必须为正整数']);
            if($name == 'approval_num' && $value <= 0) return response()->json(['status' => false, 'message' => '数量必须为正整数']);
            if($name == 'confirm_num' && $value <= 0) return response()->json(['status' => false, 'message' => '数量必须为正整数']);

            $model = Stockup::query()->find($id);
            $model->{$name} = $value;
            if(!$model->save()) throw new \Exception('更新失败!');

            DB::commit();
            return response()->json(['status' => true, 'message' => '更新成功']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    protected function _style(){
        return <<<STYLE
.table > thead > tr > th, .table > tbody > tr > td {
    white-space: nowrap;
}
.table-responsive {
    max-height: calc(80vh);
}

    table thead{
        z-index: 2;
        position: sticky;
        top: 0;
        left: 0;
        background: #fff;
    }

    /*表头*/
    table thead tr th:first-child{
        z-index: 1;
        position: sticky;
        top: 0;
        left: 0;
        background: #fff;
    }
    th:nth-child(2){
        position: sticky;
        left: 44px;
        background: #fff;
        box-shadow: 5px 0 5px -5px rgb(0 0 0 / 12%);
    }

    /*表格*/
    table tbody tr td:first-child {
        position: sticky;
        left: 0;
        background: #fff;
    }
     td:nth-child(2){
        position: sticky;
        left: 44px;
        background: #fff;
        box-shadow: 5px 0 5px -5px rgb(0 0 0 / 12%);
    }

    /*底部*/
    table tfoot tr td:first-child{
        z-index: 1;
        position: sticky;
        top: 0;
        left: 0;
        background: #fff;
    }
    td:nth-child(2){
        z-index: 1;
        position: sticky;
        left: 44px;
        background: #fff;
        box-shadow: 5px 0 5px -5px rgb(0 0 0 / 12%);
        display: table-cell;
    }
STYLE;
    }

}
